package org.apache.rocketmq.remoting.netty;

import io.netty.channel.Channel;
import org.apache.rocketmq.common.SemaphoreReleaseOnlyOnce;
import org.apache.rocketmq.remoting.InvokeCallback;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;



/**
 * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
 * @author：陈清风扬，个人微信号：chenqingfengyangjj。
 * @date:2024/12/27
 * @方法描述：该类的对象就是用来封装响应的对象，每一个请求都会对应一个ResponseFuture对象，用来判断发送的请求是否超时
 */
public class ResponseFuture {
    private final Channel channel;
    //唯一Id，一个响应要和一个请求对象，发送请求的时候会生成请求Id
    //在发送请求的时候会创建一个ResponseFuture对象，这个对象会封装接收到的响应，并且会用请求Id给该对象的opaque成员变量赋值
    private final int opaque;
    private final RemotingCommand request;
    private final long timeoutMillis;
    //收到响应后要回调的方法
    private final InvokeCallback invokeCallback;
    //开始发送请求的时间
    private final long beginTimestamp = System.currentTimeMillis();
    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    //信号量，在成功收到响应之后，该信号零应该被释放
    private final SemaphoreReleaseOnlyOnce once;

    //回调方法只执行一次的标志
    private final AtomicBoolean executeCallbackOnlyOnce = new AtomicBoolean(false);
    //接收到的响应
    private volatile RemotingCommand responseCommand;
    //请求是否发送成功的标志
    private volatile boolean sendRequestOK = true;
    private volatile Throwable cause;
    private volatile boolean interrupted = false;

    public ResponseFuture(Channel channel, int opaque, long timeoutMillis, InvokeCallback invokeCallback,
                          SemaphoreReleaseOnlyOnce once) {
        this(channel, opaque, null, timeoutMillis, invokeCallback, once);
    }

    //构造方法
    public ResponseFuture(Channel channel, int opaque, RemotingCommand request, long timeoutMillis, InvokeCallback invokeCallback,
                          SemaphoreReleaseOnlyOnce once) {
        this.channel = channel;
        this.opaque = opaque;
        this.request = request;
        this.timeoutMillis = timeoutMillis;
        this.invokeCallback = invokeCallback;
        this.once = once;
    }


    /**
     * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
     * @author：陈清风扬，个人微信号：chenqingfengyangjj。
     * @date:2024/12/27
     * @方法描述：在该方法中，接收到响应后的回调方法会被回调
     */
    public void executeInvokeCallback() {
        if (invokeCallback != null) {
            //如果定义了回调方法，并且回调方法还没有被调用
            if (this.executeCallbackOnlyOnce.compareAndSet(false, true)) {
                RemotingCommand response = getResponseCommand();
                if (response != null) {
                    //并且也成功接收到了响应，那就执行回调对象的operationSucceed方法，也就是成功接收到响应后要被回调的方法
                    invokeCallback.operationSucceed(response);
                } else {
                    if (!isSendRequestOK()) {
                        //如果没有接收到响应，请求也没发送成功，执行失败回调方法
                        invokeCallback.operationFail(new RemotingSendRequestException(channel.remoteAddress().toString(), getCause()));
                    } else if (isTimeout()) {
                        //走到这里意味着请求发送成功，但是接收响应超时了，执行失败回调方法
                        invokeCallback.operationFail(new RemotingTimeoutException(channel.remoteAddress().toString(), getTimeoutMillis(), getCause()));
                    } else {//其他异常
                        invokeCallback.operationFail(new RemotingException(getRequestCommand().toString(), getCause()));
                    }
                }//执行请求发送操作完毕的回调方法
                invokeCallback.operationComplete(this);
            }
        }
    }

    public void interrupt() {
        interrupted = true;
        executeInvokeCallback();
    }

    //释放信号量的方法
    public void release() {
        if (this.once != null) {
            this.once.release();
        }
    }

    //判断请求发送是否超时的方法，在接收到响应之后，当前ResponseFuture对象就会从responseTable这个map
    //中移除了，当定时任务执行器定期扫描响应表的时候，就会判断还在responseTable相应表中的ResponseFuture对象是否超时了
    //它还没有被从响应表中移除，就意味着它还没有收到响应，这个时候再判断他是否接收响应超时了，如果超时了就直接丢弃这个ResponseFuture对象即可
    public boolean isTimeout() {
        long diff = System.currentTimeMillis() - this.beginTimestamp;
        return diff > this.timeoutMillis;
    }


    //等待响应到来的方法，在等待响应的时候会阻塞执行当前操作的线程
    public RemotingCommand waitResponse(final long timeoutMillis) throws InterruptedException {
        this.countDownLatch.await(timeoutMillis, TimeUnit.MILLISECONDS);
        return this.responseCommand;
    }

    //把接收到的响应设置到当前ResponseFuture对象中
    public void putResponse(final RemotingCommand responseCommand) {
        this.responseCommand = responseCommand;
        //线程会结束阻塞，继续工作
        this.countDownLatch.countDown();
    }

    public long getBeginTimestamp() {
        return beginTimestamp;
    }

    public boolean isSendRequestOK() {
        return sendRequestOK;
    }

    public void setSendRequestOK(boolean sendRequestOK) {
        this.sendRequestOK = sendRequestOK;
    }

    public long getTimeoutMillis() {
        return timeoutMillis;
    }

    public InvokeCallback getInvokeCallback() {
        return invokeCallback;
    }

    public Throwable getCause() {
        return cause;
    }

    public void setCause(Throwable cause) {
        this.cause = cause;
    }

    public RemotingCommand getResponseCommand() {
        return responseCommand;
    }

    public void setResponseCommand(RemotingCommand responseCommand) {
        this.responseCommand = responseCommand;
    }

    public int getOpaque() {
        return opaque;
    }

    public RemotingCommand getRequestCommand() {
        return request;
    }

    public Channel getChannel() {
        return channel;
    }

    public boolean isInterrupted() {
        return interrupted;
    }

    @Override
    public String toString() {
        return "ResponseFuture [responseCommand=" + responseCommand + ", sendRequestOK=" + sendRequestOK
                + ", cause=" + cause + ", opaque=" + opaque + ", timeoutMillis=" + timeoutMillis
                + ", invokeCallback=" + invokeCallback + ", beginTimestamp=" + beginTimestamp
                + ", countDownLatch=" + countDownLatch + "]";
    }
}

